package com.mall.order.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.commons.tool.exception.BizException;
import com.mall.order.OrderQueryService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.converter.OrderConverter;
import com.mall.order.dal.entitys.*;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * ciggar
 * create-date: 2019/7/30-上午10:04
 */
@Slf4j
@Component
@Service
public class OrderQueryServiceImpl implements OrderQueryService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderShippingMapper orderShippingMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    OrderConverter orderConverter;


    @Override
    public OrderDetailResponse getOrderDetail(OrderDetailRequest request) {
//        request.setOrderId("19081913521928018");
        OrderDetailResponse response = new OrderDetailResponse();
        OrderDetailDto orderDetailDto = new OrderDetailDto();

        try {
            //参数检验
            request.requestCheck();

            //根据订单id查询订单商品表,得到goodsList
            List<OrderItem> orderItems = orderItemMapper.queryByOrderId(request.getOrderId());
//            Example example = new Example(OrderItem.class);
//            Example.Criteria criteria = example.createCriteria();
////            criteria.andEqualTo("orderId",request.getOrderId());
//            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
            List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItems);

            //计算商品的总金额,加上运费
            Double totalFee = orderItemDtos.get(0).getTotalFee();
            for (int i = 1; i < orderItemDtos.size(); i++) {
                totalFee += orderItemDtos.get(i).getTotalFee();
            }

//            BigDecimal totalFee = orderItemDtos.get(0).getTotalFee();
//            for (int i = 1; i < orderItemDtos.size(); i++) {
//                totalFee.add(orderItemDtos.get(i).getTotalFee());
//            }


            if (totalFee == null) {
                throw new BizException("计算商品的总金额失败");
            }
            orderDetailDto.setGoodsList(orderItemDtos);

            //现根据订单id去查询订单表，得到订单状态orderStatus
            Order order = orderMapper.selectByPrimaryKey(request.getOrderId());
            orderDetailDto.setOrderStatus(order.getStatus());

            //根据订单id查询订单物流表,得到收货人信息
            OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(request.getOrderId());

            if (orderShipping.getReceiverState() == null) {
                orderShipping.setReceiverState("");
            }
            if (orderShipping.getReceiverCity() == null) {
                orderShipping.setReceiverCity("");
            }
            if (orderShipping.getReceiverDistrict() == null) {
                orderShipping.setReceiverDistrict("");
            }
            if (orderShipping.getReceiverAddress() == null) {
                orderShipping.setReceiverAddress("");
            }
            String streetName = orderShipping.getReceiverCity() + orderShipping.getReceiverDistrict() + orderShipping.getReceiverAddress();
            orderDetailDto.setStreetName(streetName);
            orderDetailDto.setTel(orderShipping.getReceiverPhone());
            orderDetailDto.setUserId(order.getUserId().intValue());
            orderDetailDto.setUserName(orderShipping.getReceiverName());
//
            //计算订单的总金额
            Double orderTotal = totalFee.doubleValue();
            if (order.getPostFee() != null) {
                orderTotal += order.getPostFee().doubleValue();
            }
            orderDetailDto.setOrderTotal(orderTotal);

            response.setOrderDetailDto(orderDetailDto);
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            log.error("OrderCoreServiceImpl.getOrderDetail Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public OrderListResponse getOrderList(OrderListRequest request) {
        OrderListResponse orderListResponse = new OrderListResponse();

        try {
            request.requestCheck();
            Integer page = request.getPage();
            Integer size = request.getSize();
            String sort = request.getSort();
            Long userId = request.getUserId();


            PageHelper.startPage(page, size);
            Example example = new Example(Order.class);
            example.setOrderByClause(sort);
            example.createCriteria().andEqualTo("userId", userId);
            List<Order> orders = orderMapper.selectByExample(example);
            PageInfo<Order> info = new PageInfo<>(orders);
            long total = info.getTotal();
            orderListResponse.setTotal(total);
            List<OrderDetailInfo> orderDetailInfoList = new ArrayList<>();
            for (Order order : orders) {
                OrderDetailInfo orderDetailInfo = orderConverter.order2detail(order);
                List<OrderItem> orderItems = orderItemMapper.queryByOrderId(order.getOrderId());
                List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItems);
                OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(order.getOrderId());
                OrderShippingDto orderShippingDto = orderConverter.shipping2dto(orderShipping);
                orderDetailInfo.setOrderItemDto(orderItemDtos);
                orderDetailInfo.setOrderShippingDto(orderShippingDto);
                orderDetailInfoList.add(orderDetailInfo);
            }
            orderListResponse.setDetailInfoList(orderDetailInfoList);
            orderListResponse.setCode(OrderRetCode.SUCCESS.getCode());
            orderListResponse.setMsg(OrderRetCode.SUCCESS.getMessage());
        } catch (Exception e) {

            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(orderListResponse, e);
        }

        return orderListResponse;
    }

}
